﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json.Linq;
using HCQ2_Common.SQL;
using System.Runtime.Remoting.Messaging;
using HCQ2_Common.Bean;

namespace HCQ2_Common
{
    /// <summary>
    /// 语言帮助
    /// </summary>
    public static class LangHelper
    {
        /// <summary>
        /// 默认读取中文语音文件
        /// </summary>
        private static string defLanguage = Helper.ToString(SqlHelper.ExecuteScalar("SELECT item_note FROM dbo.T_ItemCode WHERE item_code='SysDefaultLanuage';"));
        private static string DefaultLangFilePath = HttpContext.Current.Server.MapPath("~/Lang/language-cn.json");

        private static JObject langFileJson;
        /// <summary>
        /// 语言内容，供后台直接使用
        /// </summary>
        public static dynamic Lang;
        public static string langName="cn";

        //static LangHelper()
        //{
        //    Init();
        //}

        /// <summary>
        ///  初始化
        /// </summary>
        /// <param name="LongName">语音文件名称，不是全程</param>
        /// <param name="throwErr">指定语句不存在时，是否抛出异常</param>
        public static void Init(string LongName=null,bool throwErr=false)
        {
            string loadLangFilePath = DefaultLangFilePath, selLang = LongName;
            if (string.IsNullOrEmpty(LongName))
            {
                if (string.IsNullOrEmpty(defLanguage))
                    defLanguage = "cn";
                selLang = defLanguage;
            }
            string virtualLangFilePath = HttpContext.Current.Server.MapPath($"~/Lang/language-{selLang.ToLower()}.json");
            langName = selLang.ToLower();
            if (!File.Exists(virtualLangFilePath))
            {
                if (throwErr)
                    throw new Exception($"指定的语言文件：{virtualLangFilePath}不存在！");
            }
            loadLangFilePath = virtualLangFilePath;
            langFileJson = ReadJsonFile(loadLangFilePath);
        }

        private static JObject ReadJsonFile(string filePath)
        {
            string langFileContent = System.IO.File.ReadAllText(filePath);
            if (!string.IsNullOrEmpty(langFileContent))
            {
                Lang = Newtonsoft.Json.JsonConvert.DeserializeObject(langFileContent);
                return JObject.Parse(langFileContent);
            }
            return null;
        }

        /// <summary>
        /// 获取语言文件内容
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetName(string key)
        {
            if (langFileJson != null)
            {
                return Convert.ToString(langFileJson[key]);
            }
            return null;
        }

        /// <summary>
        /// 获取语言文件内容
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static JObject GetObject(string key)
        {
            if (langFileJson != null)
            {
                return (JObject)langFileJson[key];
            }
            return null;
        }

        /// <summary>
        /// 获取语言文件内容
        /// 如：VRGoodManager.VRCloudManager.cloudMaterial
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="langCode">code 指定获取语言</param>
        /// <returns></returns>
        public static string GetValue(string key,string langCode="")
        {
            dynamic customLang = Lang;//默认
            string val = "null";
            try {
                if (string.IsNullOrEmpty(key))
                    return string.Empty;
                if (!string.IsNullOrEmpty(langCode))
                {
                    //自定义
                    customLang = SessionHelper.GetSessionValue("HCQ2_language_" + langCode.ToLower());
                    //customLang = CallContext.GetData("language_" + langCode.ToLower());
                    if (customLang == null)
                    {
                        string virtualLangFilePath = HttpContext.Current.Server.MapPath($"~/Lang/language-{langCode.ToLower()}.json");
                        if (File.Exists(virtualLangFilePath))
                        {
                            string langFileContent = File.ReadAllText(virtualLangFilePath);
                            if (!string.IsNullOrEmpty(langFileContent))
                            {
                                customLang = Newtonsoft.Json.JsonConvert.DeserializeObject(langFileContent);
                                SessionHelper.AddSessionValue("HCQ2_language_" + langCode.ToLower(), customLang);
                                //CallContext.SetData("language_" + langCode.ToLower(), customLang);
                            }
                        }
                    }
                }
                if (customLang != null)
                {
                    if (key.IndexOf('.') < 0)
                        return customLang[key];
                    string[] keys = key.Split('.');
                    dynamic obj = null;
                    foreach (var item in keys)
                        obj = (obj != null) ? obj[item] : customLang[item];
                    if (obj != null && obj != "")
                        val = obj;
                }
            }
            catch (Exception e) { val = "null"; }
            return val;
        }

        /// <summary>
        /// 获取语言文件数据
        /// </summary>
        /// <returns></returns>
        public static string GetJsonWrite()
        {
            string jsonWrite = string.Format("var Lang = {0};", langFileJson.ToString());
            return jsonWrite;
        }
    }
}
